package com.jet.chat.command;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jet.chat.server.ChatChannel;
import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;
import com.jet.chat.service.ChatMessage;
import com.jet.chat.service.ChatMessageService;


public class ChatCommandChangeChannel implements ChatCommand {

	@Override
	public synchronized void execute(ChatServer chatServer, ChatSession chatSession, ChatMessage chatMessage) {
		Pattern pattern = Pattern.compile("^/\\w+\\s(\\w+)$");
		Matcher matcher = pattern.matcher(chatMessage.getMessage());
		if (!matcher.matches()) {
			ChatMessageService.send(new ChatMessage("invalid command format"), chatSession.getWriter());
		} else {
			String channelName = matcher.group(1);
			ChatChannel chatChannel = chatServer.getChannel(channelName);
			
			if (chatChannel == null) {
				chatServer.getChannel(chatSession.getChannelName()).removeSession(chatSession);
				chatChannel = new ChatChannel(channelName);
				chatServer.addChannel(chatChannel);
				chatChannel.addSession(chatSession);
				chatSession.setChannelName(channelName);
				//ChatMessageService.send(new ChatMessage("you created new channel: " + channelName), chatSession.getWriter());
			} else if ( channelName.equals(chatSession.getChannelName()) ) {
				ChatMessageService.send(new ChatMessage("server > you are allready in"), chatSession.getWriter());
			} else {
				chatServer.getChannel(chatSession.getChannelName()).removeSession(chatSession);
				chatChannel.addSession(chatSession);
				chatSession.setChannelName(channelName);
				//ChatMessageService.send(new ChatMessage("you entered channel: " + channelName), chatSession.getWriter());
			}
		}
	}

}
